package com.sunday.common.mq.kafka.study.spring.e15_Error_Handling_Deserializer;

import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.log.LogAccessor;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.kafka.support.serializer.DeserializationException;
import org.springframework.kafka.support.serializer.SerializationUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * {@link org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration}
 */
@Slf4j
@RestController
@RequestMapping("/test")
public class MQApi {

    private LogAccessor logAccessor = new LogAccessor(getClass());

    @Autowired
    private KafkaTemplate<Object, Object> kafkaTemplate;

    @GetMapping("/send/{topic}/{key}")
    public void send(@PathVariable String topic, @PathVariable String key) throws InterruptedException, ExecutionException {
        CompletableFuture<SendResult<Object, Object>> future;
        future = kafkaTemplate.send(topic, key, new MyNormalObject("text"));
        log.info("[send result] : {}", future.get());
    }

    @KafkaListener(
            id = "myId_10",
            topics = "topic10",
            clientIdPrefix = "TEST10"
    )
    public void listen10(ConsumerRecord<String, BadFoo> rec) throws UnsupportedEncodingException {
        log.info("======================== {}", rec);
        DeserializationException deserEx =
                SerializationUtils.getExceptionFromHeader(
                        rec,
                        SerializationUtils.VALUE_DESERIALIZER_EXCEPTION_HEADER,
                        logAccessor);
        if (deserEx != null) {
            log.error("Record at offset {} could not be deserialized", rec.offset(), deserEx);
        }
        log.info("{}", rec.value());
        log.info("{}", new String(rec.value().getFailedDeserializationInfo().getData(), "UTF-8"));
    }

}
